﻿using UnityEngine;
using System.Collections;

public class BomberManMove : MonoBehaviour {
	public float speed = 0.4f;
	public int maxBomb = 3;
	public int bomb;
	public static int bintang = 0;
	public GameObject bombPrefab;
	Vector2 dest = Vector2.zero;
	void Start() {	
		bintang = 0;
		dest = transform.position;
	}
	void FixedUpdate() {
		Vector2 p = Vector2.MoveTowards(transform.position, dest, speed);
		rigidbody2D.MovePosition(p);
		if ((Vector2)transform.position == dest) {
			if (Input.GetKey(KeyCode.UpArrow) && valid(Vector2.up)){
				dest = (Vector2)transform.position + Vector2.up;
				//GetComponent<Animator>().enabled = true;
			}
			else if (Input.GetKey(KeyCode.RightArrow) && valid(Vector2.right)){
				dest = (Vector2)transform.position + Vector2.right;
				//GetComponent<Animator>().enabled = true;
			}
			else if (Input.GetKey(KeyCode.DownArrow) && valid(-Vector2.up)){
				dest = (Vector2)transform.position - Vector2.up;
				//GetComponent<Animator>().enabled = true;
			}
			else if (Input.GetKey(KeyCode.LeftArrow) && valid(-Vector2.right)){
				dest = (Vector2)transform.position - Vector2.right;
				//GetComponent<Animator>().enabled = true;
			}
			//else{
			//	GetComponent<Animator>().enabled = false;
			//}
			if(Input.GetKeyDown(KeyCode.Space) && bomb < maxBomb){
				Instantiate (bombPrefab,transform.position,transform.rotation);
				bomb++;
				//Instantiate(Resources.Load("Bomb"));
			}
		}
		Vector2 dir = dest - (Vector2)transform.position;
		GetComponent<Animator>().SetFloat("DirX", dir.x);
		GetComponent<Animator>().SetFloat("DirY", dir.y);
	}

	bool valid(Vector2 dir) {
		Vector2 pos = transform.position;
		RaycastHit2D hit = Physics2D.Linecast(pos + dir, pos);
		if(hit.collider.isTrigger == true)
			return true;
		return false;
	}
	public static void IncreaseStar(){
		bintang++;
		Debug.Log (bintang);
	}
	public static bool isFull(){
		Debug.Log (bintang == 3);
		return bintang == 3;
	}
}